from django.db.models import Count
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status

from artmarket.models import Artwork
from users.models import CustomUser


class Top5ArtistsStatisticView(APIView):
    def get(self, request):
        # 获取每个艺术家的作品数量并按数量降序排列，取前五名
        top_artists = Artwork.objects.values('artist').annotate(artwork_count=Count('artist')).order_by(
            '-artwork_count')[:5]
        # 获取前五名艺术家的ID列表
        top_artist_ids = [artist['artist'] for artist in top_artists]
        # 获取前五名艺术家的信息，并转换为字典以便快速查找
        artists_info = CustomUser.objects.filter(id__in=top_artist_ids).values('id', 'username', 'real_name')
        artist_info_dict = {info['id']: info for info in artists_info}
        # 构建响应数据
        response_data = []
        for artist in top_artists:
            artists_info = artist_info_dict.get(artist['artist'])
            response_data.append({
                'artist_id': artists_info['id'],
                'username': artists_info['username'],
                'real_name': artists_info['real_name'],
                'artwork_count': artist['artwork_count']
            })
        return Response(data={'data': response_data}, status=status.HTTP_200_OK)
